Micron Document
Livres et Wikis | Archives | Info


JavaScript syntax
part 34/43 Β· 161.3 KB total
layout: Wide Β· Narrow Β· Centered
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
function and contains one or more yield statements. The effect is to
return a value and pause execution at the current state. Declaring an
generator function returns an iterator. Subsequent calls to
iterator.next() resumes execution until the next yield. When the
iterator returns without using a yield statement there are no more
values and the done property of the iterator is set to true.cite-ref-21[21]

With the exception of iOS devices from Apple, generators are not
implemented for browsers on mobile devices. cite-ref-22[22]

function* generator() {
yield "red";
yield "green";
yield "blue";
}
let iterator=generator();
let current;
while(current=iterator.next().value)
console.log(current); //displays red, green then blue
console.log(iterator.next().done) //displays true

Async/await

The await operator in JavaScript can only be used from inside an async
function or at the top level of a module. If the parameter is a promise,
execution of the async function will resume when the promise is resolved
(unless the promise is rejected, in which case an error will be thrown
that can be handled with normal JavaScript exception handling). If the
parameter is not a promise, the parameter itself will be returned
immediately.cite-ref-23[23]

Many libraries provide promise objects that can also be used with await,
as long as they match the specification for native JavaScript promises.
However, promises from the jQuery library were not Promises/A+
compatible until jQuery 3.0.cite-ref-24[24]

Below is an example (modified from thiscite-ref-async-await-javascript-async-await-25-0[25] article):

async function createNewDoc() {
let response = await db.post({}); // post a new doc
return db.get(response.id); // find by id
}
async function main() {
try {
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────